Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution:

  1. public class Solution {
  2. public int maxSubArray(int[] nums) {
  3. return maxSubArray(nums, 0, nums.length - 1);
  4. }
  5. int maxSubArray(int[] nums, int lo, int hi) {
  6. if (lo == hi) {
  7. return nums[lo];
  8. }
  9. int mid = lo + (hi - lo) / 2;
  10. int left = maxSubArray(nums, lo, mid);
  11. int right = maxSubArray(nums, mid + 1, hi);
  12. int middle = maxMiddleSum(nums, lo, mid, hi);
  13. return Math.max(middle, Math.max(left, right));
  14. }
  15. int maxMiddleSum(int[] nums, int lo, int mid, int hi) {
  16. int sum = 0;
  17. int left = Integer.MIN_VALUE;
  18. for (int i = mid; i >= lo; i--) {
  19. sum += nums[i];
  20. left = Math.max(left, sum);
  21. }
  22. sum = 0;
  23. int right = Integer.MIN_VALUE;
  24. for (int i = mid + 1; i <= hi; i++) {
  25. sum += nums[i];
  26. right = Math.max(right, sum);
  27. }
  28. return left + right;
  29. }
  30. }